<?php

namespace app\api\model;

use app\api\traits\ModelTrait;
use traits\model\SoftDelete;

class UserAddressModel extends BaseModel
{

    use ModelTrait;
    use SoftDelete;

    protected $pk = 'id';
    protected $table = 'hs_user_address';
    protected static $tableName = 'user_address';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    /**
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('app\api\model\UserModel', 'user_id', 'id');
    }

    public static function exist($id, $user_id)
    {
        return self::where('id', $id)->where('user_id', $user_id)->find();
    }


    /**
     * 设置默认地址
     * @param $id
     * @param $uid
     * @return bool
     */
    public static function setDefaultAddress($id, $uid)
    {
        self::beginTrans();
        $res1 = self::where('user_id', $uid)->update(['is_default' => 0]);
        $res2 = self::where('id', $id)->where('user_id', $uid)->update(['is_default' => 1]);
        $res = $res1 !== false && $res2 !== false;
        self::checkTrans($res);
        return $res;
    }

    /**
     * 设置用户地址查询初始条件
     * @param null $model
     * @param string $prefix
     * @return \think\Model
     */
    public static function userValidAddressWhere($model = null, $prefix = '')
    {
        if ($prefix) {
            $prefix .= '.';
        }
        $model = self::getSelfModel($model);
        return $model;
    }

    //获取用户地址并分页
    public static function getUserValidAddressList($uid, $page = 1, $limit = 8, $field = '*')
    {
        if ($page) {
            return self::userValidAddressWhere()->where('user_id', $uid)->order('createtime DESC')->field($field)->page((int)$page, (int)$limit)->select() ?: [];
        } else {
            return self::userValidAddressWhere()->where('user_id', $uid)->order('createtime DESC')->field($field)->select() ?: [];
        }
    }

    //获取用户默认地址
    public static function getUserDefaultAddress($uid, $field = '*')
    {
        return self::userValidAddressWhere()->where('user_id', $uid)->where('is_default', 1)->field($field)->find();
    }
}